package com.p2p.front.util;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

/**
 * 
 * @author fansunion@qq.com 2014年11月12日
 */
public class PdfDownload {

	public static void doDownloadPdfPost(HttpServletResponse res,
			Map<String, Object> post) {
		try {
			Object title = post.get("title");
			if (title == null) {
				title = "pdf";
			}
			String goodTitle = utf8ToIso88591(title);
			String htmlContent = post.get("content").toString();
			down(res, goodTitle, htmlContent);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String utf8ToIso88591(Object title)
			throws UnsupportedEncodingException {
		return new String(title.toString().getBytes("utf-8"), "ISO8859-1");
	}

	public static void down(HttpServletResponse res, String goodTitle,
			String htmlContent) {
		pdfHeader(res, goodTitle);
		try {
			parseXHtml(res.getOutputStream(), htmlContent);
		} catch (DocumentException | IOException e) {
			e.printStackTrace();
		}
	}

	private static void pdfHeader(HttpServletResponse res, String goodTitle) {
		res.addHeader("Content-Disposition", "attachment;filename=" + goodTitle
				+ ".pdf");
		res.addHeader("Content-type", "application/pdf;charset=utf-8");
	}

	public static void parseXHtml(OutputStream out, String htmlContent)
			throws DocumentException, FileNotFoundException, IOException {
		Document document = new Document();
		PdfWriter writer = PdfWriter.getInstance(document, out);
		document.open();
		XMLWorkerHelper instance = XMLWorkerHelper.getInstance();
		InputStream stream = new ByteArrayInputStream(
				htmlContent.getBytes(Charset.forName("UTF-8")));
		// 对html格式要求很高，严格对称，比如<div></div>，css样式不行，字体要专门下载中文的
		instance.parseXHtml(writer, document, stream, null,
				Charset.forName("UTF-8"), new PdfCnFontProvider());
		document.close();
		out.close();
	}

}
